<template>
  <div class="student-grades">
    <div class="page-header">
      <h2>成绩查询</h2>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" class="filter-form">
        <el-form-item label="学期筛选">
          <el-select
            v-model="filterForm.semester"
            placeholder="请选择学期"
            style="width: 200px"
            @change="handleFilter"
          >
            <el-option label="全部学期" value="" />
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2025秋季" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :icon="Search">
            查询
          </el-button>
          <el-button @click="handleReset" :icon="Refresh">
            重置
          </el-button>
          <el-button type="success" @click="exportGrades" :icon="Download">
            导出成绩单
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 成绩统计 -->
    <el-row :gutter="20" class="stats-overview">
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Reading /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ gradeStats.totalCourses || 0 }}</div>
              <div class="stat-label">已修课程</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ gradeStats.totalCredits || 0 }}</div>
              <div class="stat-label">总学分</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ gradeStats.avgGrade || 0 }}</div>
              <div class="stat-label">平均分</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Trophy /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ gradeStats.gpa || 0 }}</div>
              <div class="stat-label">GPA</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 学习趋势和成绩分布图表 -->
    <el-row :gutter="20" class="charts-section">
      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <span>学习趋势</span>
              <span class="chart-subtitle">绩点和排名学期变化</span>
            </div>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <span>成绩分布</span>
              <span class="chart-subtitle">成绩分数段分布</span>
            </div>
          </template>
          <div ref="gradeDistChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 成绩列表 -->
    <el-card class="grades-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>成绩列表</span>
          <div class="header-actions">
            <el-button type="success" @click="exportGrades">
              <el-icon><Download /></el-icon>
              导出成绩单
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="grades-content">
        <el-table
          :data="gradesList"
          v-loading="loading"
          stripe
          border
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="70" />
          <el-table-column prop="courseName" label="课程名称" min-width="150" show-overflow-tooltip />
          <el-table-column prop="courseType" label="课程类型" width="100">
            <template #default="scope">
              <el-tag :type="getCourseTypeTag(scope.row.courseType)" size="small">
                {{ scope.row.courseType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="credit" label="学分" width="70" align="center" />
          <el-table-column prop="teacherName" label="授课教师" width="100" />
          <el-table-column prop="semester" label="学期" width="100" align="center" />
          <el-table-column prop="usualGrade" label="平时" width="80" align="center">
            <template #default="scope">
              <span :class="getScoreClass(scope.row.usualGrade)">
                {{ scope.row.usualGrade || '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="midScore" label="期中" width="80" align="center">
            <template #default="scope">
              <span :class="getScoreClass(scope.row.midScore)">
                {{ scope.row.midScore || '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="examGrade" label="期末" width="80" align="center">
            <template #default="scope">
              <span :class="getScoreClass(scope.row.examGrade)">
                {{ scope.row.examGrade || '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="finalGrade" label="总评" width="90" align="center">
            <template #default="scope">
              <el-tag :type="getGradeTag(scope.row.finalGrade)" effect="dark" size="small">
                {{ scope.row.finalGrade || '-' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="gradePoint" label="绩点" width="80" align="center">
            <template #default="scope">
              {{ scope.row.gradePoint || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="gradeLevel" label="等级" width="90" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.gradeLevel" :type="getGradeLevelTag(scope.row.gradeLevel)" size="small">
                {{ scope.row.gradeLevel }}
              </el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="120" show-overflow-tooltip>
            <template #default="scope">
              <span class="remark-text">{{ scope.row.remark || '-' }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download, Reading, Star, TrendCharts, Trophy } from '@element-plus/icons-vue'
import { getStudentGrades, getStudentCreditStats } from '../api/studentUser'
import ExcelJS from 'exceljs'
import * as echarts from 'echarts'

// 筛选表单
const filterForm = reactive({
  semester: '2024春季'
})

// 加载状态
const loading = ref(false)

// 成绩统计数据
const gradeStats = ref({
  totalCourses: 0,
  totalCredits: 0,
  avgGrade: 0,
  gpa: 0
})

// 成绩列表
const gradesList = ref([])

// 图表引用
const trendChartRef = ref(null)
const gradeDistChartRef = ref(null)
let trendChart = null
let gradeDistChart = null

// 获取课程类型标签
const getCourseTypeTag = (type) => {
  const typeMap = {
    '必修': 'primary',
    '选修': 'success',
    '实践': 'warning',
    '理论': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取成绩标签
const getGradeTag = (grade) => {
  if (!grade) return 'info'
  if (grade >= 90) return 'success'
  if (grade >= 80) return 'primary'
  if (grade >= 70) return 'warning'
  if (grade >= 60) return 'info'
  return 'danger'
}

// 获取分数样式类
const getScoreClass = (score) => {
  if (!score) return ''
  if (score >= 90) return 'score-excellent'
  if (score >= 60) return 'score-pass'
  return 'score-fail'
}

// 获取等级标签
const getGradeLevelTag = (level) => {
  const levelMap = {
    '优秀': 'success',
    '良好': 'primary',
    '中等': 'warning',
    '及格': 'info',
    '不及格': 'danger',
    // 兼容英文等级
    'A+': 'success',
    'A': 'success',
    'A-': 'primary',
    'B+': 'primary',
    'B': 'primary',
    'B-': 'warning',
    'C+': 'warning',
    'C': 'warning',
    'C-': 'info',
    'D': 'info',
    'F': 'danger'
  }
  return levelMap[level] || 'info'
}

// 获取成绩列表
const fetchGrades = async () => {
  loading.value = true
  
  try {
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    console.log('当前登录用户信息:', user)
    console.log('查询学期:', filterForm.semester)
    
    if (!user.studentId && !user.student_id) {
      ElMessage.error('请先登录')
      return
    }

    const studentId = user.studentId || user.student_id
    console.log('使用的学生ID:', studentId)
    
    const response = await getStudentGrades(studentId, filterForm.semester)
    console.log('成绩查询响应:', response)
    
    if (response.data) {
      gradesList.value = response.data
      console.log('查询到的成绩列表:', gradesList.value)
      // 计算统计数据
      calculateGradeStats(response.data)
      // 更新图表
      await nextTick()
      if (trendChart) {
        updateTrendChart()
      }
      if (gradeDistChart) {
        updateGradeDistChart()
      }
    } else {
      console.log('没有查询到成绩数据')
      gradesList.value = []
      resetGradeStats()
    }
    
  } catch (error) {
    console.error('获取成绩失败:', error)
    ElMessage.error('获取成绩失败：' + (error.message || '请检查网络连接'))
    gradesList.value = []
    resetGradeStats()
  } finally {
    loading.value = false
  }
}

// 计算成绩统计
const calculateGradeStats = (grades) => {
  if (!grades || grades.length === 0) {
    resetGradeStats()
    return
  }

  const totalCourses = grades.length
  const totalCredits = grades.reduce((sum, grade) => sum + Number(grade.credit || 0), 0)
  
  // 只统计有成绩的课程
  const gradesWithScore = grades.filter(g => g.finalGrade && Number(g.finalGrade) > 0)
  
  let avgGrade = 0
  let gpa = 0
  
  if (gradesWithScore.length > 0) {
    // 计算平均分（加权平均）
    const totalGradePoints = gradesWithScore.reduce((sum, grade) => {
      return sum + (Number(grade.finalGrade) * Number(grade.credit || 0))
    }, 0)
    const creditsWithGrade = gradesWithScore.reduce((sum, grade) => sum + Number(grade.credit || 0), 0)
    
    if (creditsWithGrade > 0) {
      avgGrade = totalGradePoints / creditsWithGrade
    }
    
    // 计算GPA（基于gradePoint加权平均）
    const totalGradePointsWeighted = gradesWithScore.reduce((sum, grade) => {
      return sum + (Number(grade.gradePoint || 0) * Number(grade.credit || 0))
    }, 0)
    
    if (creditsWithGrade > 0) {
      gpa = totalGradePointsWeighted / creditsWithGrade
    }
  }

  gradeStats.value = {
    totalCourses,
    totalCredits,
    avgGrade: Math.round(avgGrade * 100) / 100,
    gpa: Math.round(gpa * 100) / 100
  }
}

// 重置成绩统计
const resetGradeStats = () => {
  gradeStats.value = {
    totalCourses: 0,
    totalCredits: 0,
    avgGrade: 0,
    gpa: 0
  }
}

// 初始化学习趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value) return
  
  if (trendChart) {
    trendChart.dispose()
  }
  
  trendChart = echarts.init(trendChartRef.value)
  updateTrendChart()
}

// 更新学习趋势图表数据
const updateTrendChart = () => {
  if (!trendChart) return
  
  // 按学期分组计算数据
  const semesterMap = new Map()
  
  gradesList.value.forEach(grade => {
    const semester = grade.semester
    if (!semesterMap.has(semester)) {
      semesterMap.set(semester, {
        semester: semester,
        totalGrade: 0,
        totalCredit: 0,
        gradeCount: 0,
        credits: 0
      })
    }
    
    const data = semesterMap.get(semester)
    if (grade.finalGrade && Number(grade.finalGrade) > 0) {
      data.totalGrade += Number(grade.finalGrade) * Number(grade.credit || 0)
      data.totalCredit += Number(grade.credit || 0)
      data.gradeCount++
    }
    data.credits += Number(grade.credit || 0)
  })
  
  // 转换为数组并排序
  const semesterData = Array.from(semesterMap.values()).sort((a, b) => {
    return a.semester.localeCompare(b.semester)
  })
  
  // 计算每个学期的平均绩点
  const semesters = semesterData.map(d => d.semester)
  const avgGrades = semesterData.map(d => {
    return d.totalCredit > 0 ? (d.totalGrade / d.totalCredit).toFixed(1) : 0
  })
  const credits = semesterData.map(d => d.credits)
  
  // 模拟排名数据（从高到低，排名越小越好）
  const rankings = semesterData.map((_, index) => {
    // 简单模拟：根据平均分计算排名
    const avgScore = avgGrades[index]
    if (avgScore >= 90) return Math.floor(Math.random() * 3) + 1 // 1-3名
    if (avgScore >= 85) return Math.floor(Math.random() * 5) + 3 // 3-8名
    if (avgScore >= 80) return Math.floor(Math.random() * 10) + 8 // 8-18名
    return Math.floor(Math.random() * 20) + 18 // 18-38名
  })
  
  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e4e7ed',
      borderWidth: 1,
      textStyle: {
        color: '#606266'
      },
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['排名', '绩点', '学分'],
      top: 10,
      textStyle: {
        fontSize: 12,
        color: '#606266'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '50',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: semesters,
      axisLine: {
        lineStyle: {
          color: '#d0d0d0'
        }
      },
      axisLabel: {
        color: '#606266',
        fontSize: 11
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '排名/绩点',
        position: 'left',
        axisLine: {
          lineStyle: {
            color: '#d0d0d0'
          }
        },
        axisLabel: {
          color: '#606266',
          fontSize: 11
        },
        splitLine: {
          lineStyle: {
            color: '#e4e7ed',
            type: 'dashed'
          }
        }
      },
      {
        type: 'value',
        name: '学分',
        position: 'right',
        axisLine: {
          lineStyle: {
            color: '#d0d0d0'
          }
        },
        axisLabel: {
          color: '#606266',
          fontSize: 11
        },
        splitLine: {
          show: false
        }
      }
    ],
    series: [
      {
        name: '排名',
        type: 'line',
        data: rankings,
        smooth: true,
        lineStyle: {
          color: '#409EFF',
          width: 3
        },
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.05)' }
          ])
        },
        emphasis: {
          focus: 'series'
        }
      },
      {
        name: '绩点',
        type: 'line',
        data: avgGrades,
        smooth: true,
        lineStyle: {
          color: '#67C23A',
          width: 3
        },
        itemStyle: {
          color: '#67C23A'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
            { offset: 1, color: 'rgba(103, 194, 58, 0.05)' }
          ])
        },
        emphasis: {
          focus: 'series'
        }
      },
      {
        name: '学分',
        type: 'line',
        yAxisIndex: 1,
        data: credits,
        smooth: true,
        lineStyle: {
          color: '#E6A23C',
          width: 3
        },
        itemStyle: {
          color: '#E6A23C'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(230, 162, 60, 0.3)' },
            { offset: 1, color: 'rgba(230, 162, 60, 0.05)' }
          ])
        },
        emphasis: {
          focus: 'series'
        }
      }
    ]
  }
  
  trendChart.setOption(option)
}

// 初始化成绩分布图表
const initGradeDistChart = () => {
  if (!gradeDistChartRef.value) return
  
  if (gradeDistChart) {
    gradeDistChart.dispose()
  }
  
  gradeDistChart = echarts.init(gradeDistChartRef.value)
  updateGradeDistChart()
}

// 更新成绩分布图表数据
const updateGradeDistChart = () => {
  if (!gradeDistChart) return
  
  // 统计各等级数量
  const distribution = {
    '优秀': 0,
    '良好': 0,
    '中等': 0,
    '及格': 0,
    '不及格': 0
  }
  
  gradesList.value.forEach(grade => {
    const finalGrade = Number(grade.finalGrade)
    if (!isNaN(finalGrade) && finalGrade > 0) {
      if (finalGrade >= 90) {
        distribution['优秀']++
      } else if (finalGrade >= 80) {
        distribution['良好']++
      } else if (finalGrade >= 70) {
        distribution['中等']++
      } else if (finalGrade >= 60) {
        distribution['及格']++
      } else {
        distribution['不及格']++
      }
    }
  })
  
  const categories = Object.keys(distribution)
  const values = Object.values(distribution)
  
  const option = {
    title: {
      text: '成绩分数段分布',
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 14,
        color: '#606266',
        fontWeight: 500
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e4e7ed',
      borderWidth: 1,
      textStyle: {
        color: '#606266'
      },
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        const item = params[0]
        return `${item.name}<br/>课程数量: ${item.value}`
      }
    },
    legend: {
      data: ['课程数量'],
      top: 40,
      textStyle: {
        fontSize: 12,
        color: '#606266'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '80',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisLine: {
        lineStyle: {
          color: '#d0d0d0'
        }
      },
      axisLabel: {
        color: '#606266',
        fontSize: 12,
        fontWeight: 500
      }
    },
    yAxis: {
      type: 'value',
      name: '课程数量',
      minInterval: 1,
      axisLine: {
        lineStyle: {
          color: '#d0d0d0'
        }
      },
      axisLabel: {
        color: '#606266',
        fontSize: 11
      },
      splitLine: {
        lineStyle: {
          color: '#e4e7ed',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '课程数量',
        type: 'bar',
        data: values.map((value, index) => {
          const colors = ['#67C23A', '#409EFF', '#E6A23C', '#909399', '#F56C6C']
          return {
            value: value,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: colors[index] },
                { offset: 1, color: colors[index] + 'CC' }
              ])
            }
          }
        }),
        barWidth: '50%',
        label: {
          show: true,
          position: 'top',
          color: '#606266',
          fontSize: 14,
          fontWeight: 'bold'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          }
        }
      }
    ]
  }
  
  gradeDistChart.setOption(option)
}

// 筛选
const handleFilter = () => {
  fetchGrades()
}

// 重置筛选
const handleReset = () => {
  filterForm.semester = '2025-1'
  fetchGrades()
}

// 导出成绩单 - 使用ExcelJS生成精美个人成绩单
const exportGrades = async () => {
  if (!gradesList.value || gradesList.value.length === 0) {
    ElMessage.warning('暂无成绩数据可导出')
    return
  }
  
  try {
    // 获取学生信息
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    const studentName = user.stuName || user.name || '学生'
    const studentNo = user.stuNo || user.studentNo || ''
    
    // 创建工作簿
    const workbook = new ExcelJS.Workbook()
    workbook.creator = studentName
    workbook.created = new Date()
    
    // ================ 工作表1：个人成绩单 ================
    const sheet1 = workbook.addWorksheet('我的成绩单')
    
    // 设置列宽
    sheet1.columns = [
      { width: 8 },   // 序号
      { width: 20 },  // 课程名称
      { width: 12 },  // 课程类型
      { width: 8 },   // 学分
      { width: 12 },  // 授课教师
      { width: 12 },  // 学期
      { width: 10 },  // 平时
      { width: 10 },  // 期中
      { width: 10 },  // 期末
      { width: 10 },  // 总评
      { width: 8 },   // 绩点
      { width: 10 },  // 等级
      { width: 20 }   // 备注
    ]
    
    // 添加标题（合并单元格）
    sheet1.mergeCells('A1:M1')
    const titleCell = sheet1.getCell('A1')
    titleCell.value = `${studentName} (${studentNo}) 的成绩单`
    titleCell.font = { bold: true, size: 18, color: { argb: 'FF2C3E50' } }
    titleCell.alignment = { vertical: 'middle', horizontal: 'center' }
    titleCell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFF0F2F5' }
    }
    sheet1.getRow(1).height = 40
    
    // 添加统计信息行
    sheet1.mergeCells('A2:F2')
    const statsCell = sheet1.getCell('A2')
    statsCell.value = `已修课程: ${gradeStats.value.totalCourses}   总学分: ${gradeStats.value.totalCredits}   平均分: ${gradeStats.value.avgGrade}   GPA: ${gradeStats.value.gpa}`
    statsCell.font = { size: 11, color: { argb: 'FF606266' } }
    statsCell.alignment = { vertical: 'middle', horizontal: 'left' }
    statsCell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFFAFBFC' }
    }
    sheet1.getRow(2).height = 28
    
    // 添加导出信息
    sheet1.mergeCells('G2:M2')
    const exportInfoCell = sheet1.getCell('G2')
    const semesterText = filterForm.semester ? `学期: ${filterForm.semester}` : '全部学期'
    exportInfoCell.value = `${semesterText}   导出时间: ${new Date().toLocaleString('zh-CN')}`
    exportInfoCell.font = { size: 11, color: { argb: 'FF606266' } }
    exportInfoCell.alignment = { vertical: 'middle', horizontal: 'right' }
    exportInfoCell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFFAFBFC' }
    }
    
    // 添加表头
    const headerRow = sheet1.addRow([
      '序号', '课程名称', '课程类型', '学分', '授课教师', '学期',
      '平时', '期中', '期末', '总评', '绩点', '等级', '备注'
    ])
    headerRow.height = 30
    headerRow.font = { bold: true, size: 11, color: { argb: 'FFFFFFFF' } }
    headerRow.alignment = { vertical: 'middle', horizontal: 'center' }
    headerRow.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FF5470C6' }
    }
    
    // 添加成绩数据
    gradesList.value.forEach((grade, index) => {
      const row = sheet1.addRow([
        index + 1,
        grade.courseName || '',
        grade.courseType || '',
        grade.credit || '',
        grade.teacherName || '',
        grade.semester || '',
        grade.usualGrade || '-',
        grade.midScore || '-',
        grade.examGrade || '-',
        grade.finalGrade || '-',
        grade.gradePoint || '-',
        grade.gradeLevel || '-',
        grade.remark || ''
      ])
      
      row.height = 24
      row.alignment = { vertical: 'middle', horizontal: 'center' }
      
      // 序号列加粗
      row.getCell(1).font = { bold: true }
      
      // 课程名称列左对齐
      row.getCell(2).alignment = { vertical: 'middle', horizontal: 'left' }
      
      // 备注列左对齐
      row.getCell(13).alignment = { vertical: 'middle', horizontal: 'left' }
      
      // 根据分数设置颜色
      const finalGrade = parseFloat(grade.finalGrade)
      if (!isNaN(finalGrade)) {
        // 平时、期中、期末成绩单元格颜色
        [7, 8, 9].forEach(colIndex => {
          const cell = row.getCell(colIndex)
          const score = parseFloat(cell.value)
          if (!isNaN(score)) {
            if (score >= 90) {
              cell.font = { color: { argb: 'FF67C23A' }, bold: true }
            } else if (score >= 80) {
              cell.font = { color: { argb: 'FF409EFF' }, bold: true }
            } else if (score >= 60) {
              cell.font = { color: { argb: 'FFE6A23C' }, bold: true }
            } else {
              cell.font = { color: { argb: 'FFF56C6C' }, bold: true }
            }
          }
        })
        
        // 总评成绩单元格（重点标记）
        const totalCell = row.getCell(10)
        if (finalGrade >= 90) {
          totalCell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFE7F9E7' }
          }
          totalCell.font = { color: { argb: 'FF67C23A' }, bold: true, size: 12 }
        } else if (finalGrade >= 80) {
          totalCell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFE1F3FF' }
          }
          totalCell.font = { color: { argb: 'FF409EFF' }, bold: true, size: 12 }
        } else if (finalGrade >= 70) {
          totalCell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFFEF7E7' }
          }
          totalCell.font = { color: { argb: 'FFE6A23C' }, bold: true, size: 12 }
        } else if (finalGrade >= 60) {
          totalCell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFF0F9FF' }
          }
          totalCell.font = { color: { argb: 'FF909399' }, bold: true, size: 12 }
        } else {
          totalCell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFFEF0F0' }
          }
          totalCell.font = { color: { argb: 'FFF56C6C' }, bold: true, size: 12 }
        }
        
        // 等级单元格
        const levelCell = row.getCell(12)
        const levelColors = {
          '优秀': { bg: 'FFE7F9E7', fg: 'FF67C23A' },
          '良好': { bg: 'FFE1F3FF', fg: 'FF409EFF' },
          '中等': { bg: 'FFFEF7E7', fg: 'FFE6A23C' },
          '及格': { bg: 'FFF0F9FF', fg: 'FF909399' },
          '不及格': { bg: 'FFFEF0F0', fg: 'FFF56C6C' }
        }
        const levelColor = levelColors[grade.gradeLevel]
        if (levelColor) {
          levelCell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: levelColor.bg }
          }
          levelCell.font = { color: { argb: levelColor.fg }, bold: true }
        }
        
        // 课程类型标签
        const typeCell = row.getCell(3)
        const typeColors = {
          '必修': { bg: 'FFE1F3FF', fg: 'FF409EFF' },
          '选修': { bg: 'FFE7F9E7', fg: 'FF67C23A' },
          '实践': { bg: 'FFFEF7E7', fg: 'FFE6A23C' },
          '理论': { bg: 'FFF0F2F5', fg: 'FF909399' }
        }
        const typeColor = typeColors[grade.courseType]
        if (typeColor) {
          typeCell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: typeColor.bg }
          }
          typeCell.font = { color: { argb: typeColor.fg }, bold: true }
        }
      }
      
      // 斑马纹效果
      if (index % 2 === 1) {
        for (let i = 1; i <= 13; i++) {
          const cell = row.getCell(i)
          if (!cell.fill || !cell.fill.fgColor) {
            cell.fill = {
              type: 'pattern',
              pattern: 'solid',
              fgColor: { argb: 'FFF9FAFB' }
            }
          }
        }
      }
    })
    
    // 添加边框
    sheet1.eachRow((row, rowNumber) => {
      if (rowNumber >= 1) {
        row.eachCell((cell) => {
          cell.border = {
            top: { style: 'thin', color: { argb: 'FFD0D0D0' } },
            left: { style: 'thin', color: { argb: 'FFD0D0D0' } },
            bottom: { style: 'thin', color: { argb: 'FFD0D0D0' } },
            right: { style: 'thin', color: { argb: 'FFD0D0D0' } }
          }
        })
      }
    })
    
    // ================ 工作表2：学习分析 ================
    const sheet2 = workbook.addWorksheet('学习分析')
    
    // 设置列宽
    sheet2.columns = [
      { width: 25 },  // 统计项
      { width: 20 }   // 统计值
    ]
    
    // 添加标题
    sheet2.mergeCells('A1:B1')
    const statTitleCell = sheet2.getCell('A1')
    statTitleCell.value = '学习情况分析'
    statTitleCell.font = { bold: true, size: 18, color: { argb: 'FF2C3E50' } }
    statTitleCell.alignment = { vertical: 'middle', horizontal: 'center' }
    statTitleCell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFF0F2F5' }
    }
    sheet2.getRow(1).height = 40
    
    // 添加空行
    sheet2.addRow([])
    
    // 基本信息
    const basicInfo = [
      { label: '学生姓名', value: studentName },
      { label: '学号', value: studentNo },
      { label: '查询学期', value: filterForm.semester || '全部学期' },
      { label: '导出时间', value: new Date().toLocaleString('zh-CN') }
    ]
    
    basicInfo.forEach((item) => {
      const row = sheet2.addRow([item.label, item.value])
      row.height = 28
      row.getCell(1).font = { bold: true, size: 12 }
      row.getCell(1).alignment = { vertical: 'middle', horizontal: 'right' }
      row.getCell(1).fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFF5F7FA' }
      }
      row.getCell(2).font = { size: 12, color: { argb: 'FF2C3E50' } }
      row.getCell(2).alignment = { vertical: 'middle', horizontal: 'left' }
      row.eachCell((cell) => {
        cell.border = {
          top: { style: 'thin', color: { argb: 'FFD0D0D0' } },
          left: { style: 'thin', color: { argb: 'FFD0D0D0' } },
          bottom: { style: 'thin', color: { argb: 'FFD0D0D0' } },
          right: { style: 'thin', color: { argb: 'FFD0D0D0' } }
        }
      })
    })
    
    // 添加空行
    sheet2.addRow([])
    sheet2.addRow([])
    
    // 学习统计
    sheet2.mergeCells(`A${sheet2.rowCount + 1}:B${sheet2.rowCount + 1}`)
    const studyStatTitleCell = sheet2.getCell(`A${sheet2.rowCount}`)
    studyStatTitleCell.value = '学习统计'
    studyStatTitleCell.font = { bold: true, size: 14, color: { argb: 'FF2C3E50' } }
    studyStatTitleCell.alignment = { vertical: 'middle', horizontal: 'center' }
    studyStatTitleCell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFE8F4F8' }
    }
    sheet2.getRow(sheet2.rowCount).height = 30
    
    const studyStats = [
      { label: '已修课程数', value: gradeStats.value.totalCourses },
      { label: '总学分', value: gradeStats.value.totalCredits },
      { label: '加权平均分', value: gradeStats.value.avgGrade },
      { label: 'GPA (绩点)', value: gradeStats.value.gpa }
    ]
    
    studyStats.forEach((item, index) => {
      const row = sheet2.addRow([item.label, item.value])
      row.height = 28
      row.getCell(1).font = { bold: true, size: 12 }
      row.getCell(1).alignment = { vertical: 'middle', horizontal: 'right' }
      row.getCell(1).fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFF5F7FA' }
      }
      row.getCell(2).font = { size: 14, color: { argb: 'FF409EFF' }, bold: true }
      row.getCell(2).alignment = { vertical: 'middle', horizontal: 'center' }
      row.eachCell((cell) => {
        cell.border = {
          top: { style: 'thin', color: { argb: 'FFD0D0D0' } },
          left: { style: 'thin', color: { argb: 'FFD0D0D0' } },
          bottom: { style: 'thin', color: { argb: 'FFD0D0D0' } },
          right: { style: 'thin', color: { argb: 'FFD0D0D0' } }
        }
      })
    })
    
    // 添加空行
    sheet2.addRow([])
    sheet2.addRow([])
    
    // 课程类型统计
    sheet2.mergeCells(`A${sheet2.rowCount + 1}:B${sheet2.rowCount + 1}`)
    const courseTypeTitleCell = sheet2.getCell(`A${sheet2.rowCount}`)
    courseTypeTitleCell.value = '课程类型分布'
    courseTypeTitleCell.font = { bold: true, size: 14, color: { argb: 'FF2C3E50' } }
    courseTypeTitleCell.alignment = { vertical: 'middle', horizontal: 'center' }
    courseTypeTitleCell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFE8F4F8' }
    }
    sheet2.getRow(sheet2.rowCount).height = 30
    
    // 计算课程类型分布
    const courseTypeCount = {}
    gradesList.value.forEach(grade => {
      const type = grade.courseType || '其他'
      courseTypeCount[type] = (courseTypeCount[type] || 0) + 1
    })
    
    // 添加表头
    const typeHeaderRow = sheet2.addRow(['课程类型', '数量'])
    typeHeaderRow.height = 25
    typeHeaderRow.font = { bold: true, size: 11, color: { argb: 'FFFFFFFF' } }
    typeHeaderRow.alignment = { vertical: 'middle', horizontal: 'center' }
    typeHeaderRow.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FF70AD47' }
    }
    
    Object.entries(courseTypeCount).forEach(([type, count], index) => {
      const row = sheet2.addRow([type, count])
      row.height = 24
      row.getCell(1).alignment = { vertical: 'middle', horizontal: 'left' }
      row.getCell(2).alignment = { vertical: 'middle', horizontal: 'center' }
      row.getCell(2).font = { bold: true, color: { argb: 'FF409EFF' }, size: 12 }
      
      if (index % 2 === 1) {
        row.fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: 'FFF9FAFB' }
        }
      }
      
      row.eachCell((cell) => {
        cell.border = {
          top: { style: 'thin', color: { argb: 'FFD0D0D0' } },
          left: { style: 'thin', color: { argb: 'FFD0D0D0' } },
          bottom: { style: 'thin', color: { argb: 'FFD0D0D0' } },
          right: { style: 'thin', color: { argb: 'FFD0D0D0' } }
        }
      })
    })
    
    // 生成文件名
    const semester = filterForm.semester || '全部学期'
    const fileName = `${studentName}_成绩单_${semester}_${new Date().toLocaleDateString().replace(/\//g, '-')}.xlsx`
    
    // 导出文件
    const buffer = await workbook.xlsx.writeBuffer()
    const blob = new Blob([buffer], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success(`成功导出 ${gradesList.value.length} 门课程的成绩！`)
  } catch (error) {
    console.error('导出成绩单失败:', error)
    ElMessage.error('导出成绩单失败: ' + error.message)
  }
}

// 组件挂载时获取数据
onMounted(async () => {
  await nextTick()
  initTrendChart()
  initGradeDistChart()
  fetchGrades()
  
  // 窗口大小改变时重新绘制图表
  window.addEventListener('resize', () => {
    if (trendChart) {
      trendChart.resize()
    }
    if (gradeDistChart) {
      gradeDistChart.resize()
    }
  })
})
</script>

<style scoped>
.student-grades {
  background: #f5f7fa;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
  letter-spacing: 1px;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
}

.filter-card :deep(.el-card__body) {
  padding: 20px;
}

.filter-form {
  margin-bottom: 0;
}

.filter-form :deep(.el-form-item) {
  margin-bottom: 16px;
  margin-right: 24px;
}

.filter-form :deep(.el-form-item__label) {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.stats-overview {
  margin-bottom: 20px;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
  overflow: hidden;
}

.chart-card :deep(.el-card__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-bottom: none;
  padding: 16px 20px;
}

.chart-header {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.chart-header span:first-child {
  color: #ffffff;
  font-weight: 600;
  font-size: 16px;
}

.chart-subtitle {
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
  font-weight: 400;
}

.chart-container {
  width: 100%;
  height: 350px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.stat-card :deep(.el-card__body) {
  padding: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-size: 24px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.grades-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
  overflow: hidden;
}

.grades-card :deep(.el-card__header) {
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 16px 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  color: #2c3e50;
  font-weight: 600;
  font-size: 16px;
}

.header-actions .el-button {
  border-radius: 4px;
  font-weight: 500;
  padding: 8px 16px;
  transition: all 0.3s ease;
}

.grades-content {
  padding: 0;
}

.grades-content :deep(.el-table) {
  border-radius: 0;
}

.grades-content :deep(.el-table__header) {
  background: #f5f7fa;
}

.grades-content :deep(.el-table th) {
  background: transparent;
  color: #2c3e50;
  font-weight: 600;
  font-size: 14px;
  border-bottom: 1px solid #ebeef5;
  padding: 12px;
}

.grades-content :deep(.el-table td) {
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
  color: #606266;
  font-size: 14px;
}

.grades-content :deep(.el-table__row:hover) {
  background: #f5f7fa;
}

.grades-content :deep(.el-table__row:nth-child(even)) {
  background: #fafafa;
}

.grades-content :deep(.el-table__row:nth-child(even):hover) {
  background: #f5f7fa;
}

.grades-content :deep(.el-button) {
  border-radius: 4px;
  font-weight: 500;
  padding: 6px 12px;
  font-size: 12px;
  transition: all 0.3s ease;
}

/* 成绩分数着色 */
.score-excellent {
  color: #67c23a;
  font-weight: 600;
}

.score-pass {
  color: #409eff;
  font-weight: 500;
}

.score-fail {
  color: #f56c6c;
  font-weight: 600;
}

.remark-text {
  color: #909399;
  font-size: 13px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .student-grades {
    padding: 16px;
  }
  
  .page-header h2 {
    font-size: 24px;
  }
  
  .stats-overview {
    margin-bottom: 16px;
  }
  
  .charts-section {
    margin-bottom: 16px;
  }
  
  .chart-container {
    height: 280px;
  }
  
  .stat-content {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
  
  .stat-icon {
    width: 50px;
    height: 50px;
    font-size: 20px;
  }
  
  .stat-value {
    font-size: 24px;
  }
  
  .filter-form :deep(.el-form-item) {
    margin-right: 0;
    width: 100%;
  }
  
  .filter-form :deep(.el-input),
  .filter-form :deep(.el-select) {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .student-grades {
    padding: 12px;
  }
  
  .page-header h2 {
    font-size: 20px;
  }
  
  .filter-card :deep(.el-card__body) {
    padding: 16px;
  }
  
  .stat-card :deep(.el-card__body) {
    padding: 16px;
  }
  
  .chart-container {
    height: 240px;
  }
  
  .stat-icon {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }
  
  .stat-value {
    font-size: 20px;
  }
  
  .grades-content :deep(.el-table th),
  .grades-content :deep(.el-table td) {
    padding: 12px 8px;
    font-size: 13px;
  }
}
</style>












